/**
 * 
 */
package com.imonsoft.sqm.web.common;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.imonsoft.common.constant.CCommon;
import com.imonsoft.common.exception.SystemException;
import com.imonsoft.common.httpModel.ReturnMessage;
import com.imonsoft.common.util.AjaxUtil;
import com.imonsoft.common.util.JsonUtil;
import com.imonsoft.sqm.pojo.sys.User;
import com.imonsoft.sqm.service.sys.UserService;

/**
 * 用户登录/退出控制器
 * 
 * @author LiQianHui
 * @date 2013-04-17
 * @version 2013
 */
@Controller
public class LoginController {

	@Autowired
	private UserService userService;
	protected final Log logger = LogFactory.getLog(getClass());

	@RequestMapping(value = "/ajaxLogin.do")
	public void login(HttpServletResponse response, User user) {
		ReturnMessage message = new ReturnMessage();
		try {
			boolean isTrue = userService.checkUser(user);
			if (isTrue) {
				message.setSuccess(true);
			}
		} catch (SystemException se) {
			logger.info(se.getMessage());
			message.setMsg(se.getMessage());
		} catch (CannotGetJdbcConnectionException e) {
			logger.error(e.getMessage());
			message.setMsg("登录失败：连接数据库异常！");
		} catch (Exception e) {
			logger.error(e.getMessage());
			message.setMsg("登录失败：" + e.getMessage());
		}
		AjaxUtil.renderJSON(response, JsonUtil.bean2json(message));
	}

	@RequestMapping("/logout.do")
	public String logout(HttpSession session) {
		if (logger.isDebugEnabled()) {
			logger.debug("退出系统！");
		}
		Object userInfo = (Object) session.getAttribute(CCommon.USER_INFO);
		if (userInfo != null) {
			// 写日志
			// ....
		}
		session.invalidate();
		return "redirect:index.do";
	}
}
